package edu.pxd.cecs.ece510.pocketmanager;


import java.util.ArrayList;

import android.os.Bundle;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.content.DialogInterface;

public class AddexpenseActivity extends Activity {
	public static final String EVENT_GET_POSITION_KEY = "edu.pxd.cecs.ece510.pocketmanager.event_getposition";
	CreateActivity c;
	private String EventTable = "EventTable";
	private  Button mCreateButton;
	private ArrayList<String> valueArr;
	public float[] listAmount;
	public float payedAmount;
	public float totalAmount = 0;
	 ListView list1;
	    String[] name = {    		
	    };
		String[]amount1 = {
		};
		String temp1;

		float[] fillAmount;
	 ExpenseList E;
	 String fetchEvent;	
	 int count3;
	  private int eventPosition;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addexpenses);
		
		eventPosition = getIntent().getIntExtra(EVENT_GET_POSITION_KEY,0);
		Log.d("eventPosition", String.valueOf(eventPosition));
		
		Cursor eventLook = CreateActivity.db.rawQuery("SELECT * from " + EventTable, null);
		int count2 = eventLook.getCount();
		eventPosition = count2;
		eventLook.moveToPosition(eventPosition-1);
		fetchEvent = eventLook.getString(eventLook.getColumnIndex("eventname")).replaceAll(" ",""); 
		Log.d("EVENT", fetchEvent);
		
		Cursor nameLook = CreateActivity.db.rawQuery("SELECT * from " + fetchEvent, null);
		count3 = nameLook.getCount();
		nameLook.moveToFirst();
		name = new String[count3];
		amount1 = new String[count3] ;
		listAmount = new float [count3];
		fillAmount= new float[count3];
		for(int track1 = 0;track1 < count3; track1++)
		{
			temp1 = nameLook.getString(nameLook.getColumnIndex("personeName"));
			Log.d("NAME", temp1);
			name[track1] = temp1;
			amount1[track1] = String.valueOf(nameLook.getFloat(nameLook.getColumnIndex("amountPay")));
			Log.d("AMOUNT", amount1[track1]);
			listAmount[track1] = nameLook.getFloat(nameLook.getColumnIndex("amountPay"));
			nameLook.moveToNext();
		}
		
		 final ExpenseList adapter = new ExpenseList(AddexpenseActivity.this, name, amount1);

	     list1=(ListView)findViewById(R.id.listView_expense);
	     list1.setAdapter(adapter);
	     list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	    	 
	            @Override
	            public void onItemClick(AdapterView<?> parent, View view,
	                                    final int position, long id) {
	            //    Toast.makeText(CreateActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();

	           
	    // list1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			//	@Override
		//		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			//			int arg2, long arg3) {					
            	
					/*View v = (View)view.getParent();
					EditText ed1 = (EditText) v.findViewById(R.id.expense);
					ed1.setVisibility(View.VISIBLE);
					adapter.notifyDataSetChanged();
              Toast.makeText(AddexpenseActivity.this, "You Clicked at " +name[+ position], Toast.LENGTH_SHORT).show();
*/				
            	Log.d("edittext","edit");
            	Toast.makeText(getApplicationContext(),"Right", Toast.LENGTH_SHORT).show();
            	AlertDialog.Builder alertDialog = new AlertDialog.Builder(AddexpenseActivity.this);

                 // Setting Dialog Title
                 alertDialog.setTitle("AMOUNT");

                 // Setting Dialog Message
                 alertDialog.setMessage("Enter Amount");
                 final EditText input = new EditText(AddexpenseActivity.this);
                // input.setInputType(InputType.TYPE_CLASS_NUMBER);
                 //input.setKeyListener(DigitsKeyListener.getInstance());
                 LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                         LinearLayout.LayoutParams.MATCH_PARENT,
                                         LinearLayout.LayoutParams.MATCH_PARENT);
                   input.setLayoutParams(lp);
                   alertDialog.setView(input);

                   
                 // Setting Icon to Dialog
                 //alertDialog.setIcon(R.drawable.key);

                 // Setting Positive "Yes" Button
                   alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener(){
                   //alertDialog.setPositiveButton("YES",new DialogInterface.OnClickListener()   {
                             public void onClick(DialogInterface dialog,int which) {
                                 // Write your code here to execute after dialog

                                 String newtest = input.getText().toString();
                                 if(newtest.compareTo("")==0)
                                 {
                                	 Toast.makeText(getApplicationContext(),"Wrong Value", Toast.LENGTH_SHORT).show();
                                 }
                                 else{
                                	 Log.d("edittext", newtest);
                                	 Float xyz = Float.valueOf(newtest);
                                	 //amount1[position] = newtest;
                                	 listAmount[position] = listAmount[position] + xyz; 
                                	 listAmount[position] = (float)(Math.round(listAmount[position]*100.0)/100.0);
                                	 amount1[position] = String.valueOf(listAmount[position]);
                                	 final ExpenseList adapter1 = new ExpenseList(AddexpenseActivity.this, name, amount1);
                                	 list1=(ListView)findViewById(R.id.listView_expense);
                            	     list1.setAdapter(adapter1);
                                 }
                                	 
                             }
                         });
                 // Setting Negative "NO" Button
                 alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                             public void onClick(DialogInterface dialog, int which) {
                                 // Write your code here to execute after dialog
                                 dialog.cancel();
                             }
                         });

                 // closed

                 // Showing Alert Message
                 alertDialog.show();
				//return false;
             }
         });
	    mCreateButton = (Button)findViewById(R.id.continuebutton1);
	    mCreateButton.setOnClickListener(new View.OnClickListener() {
	    
	    @Override
		public void onClick(View v) {
	    	    /** get all values of the EditText-Fields */
	    	 /*   ArrayList<String> mannschaftsnamen = new ArrayList<String>();
	    	    EditText et;
	    	    for (int i = 0; i < list.getCount(); i++) {
	    	        v = list.getAdapter().getView(i, null, null);
	    	        et = (EditText) v.findViewById(i);
	    	        mannschaftsnamen.add(et.getText().toString());
	    	    }*/
			//EditText ed1 = (EditText) v.findViewById(R.id.expense);
	    	//final ExpenseList adapter1 = new ExpenseList(AddexpenseActivity.this, name, amount1);
	    	//int test = E.getEditValue(1);
			//c.screenUpdate();
			
	    	//Intent i = new Intent(AddexpenseActivity.this, ExpensesActivity.class);
	    	//startActivity(i);
	    	int arrSize =  count3;
	    	for(int i= 0; i< arrSize; i++)
			{
				Log.d("amount", amount1[i]);
				String strSQL = "UPDATE'" + fetchEvent + "'SET amountPay = '"+ listAmount[i] + "' WHERE personeName = '"+ name[i] +"'";
				CreateActivity.db.execSQL(strSQL);
				//final String valueNew = "UPDATE'" + fetchEvent + "'SET'" + amountPay =amount1[i]  ";
				//CreateActivity.db.execSQL(valueNew);
			}
			//final String newValue = "INSERT INTO '" + tableName + "' VALUES('xyz','500', '20');";
			//CreateActivity.db.execSQL(newValue);
			Cursor idTable = CreateActivity.db.rawQuery("SELECT * from " + fetchEvent, null);
			int count1 = idTable.getCount();
			idTable.moveToFirst();
			for(int track1 = 0;track1 < count1; track1++)
			{
				Log.d("NAME", idTable.getString(idTable.getColumnIndex("personeName")));
				Log.d("amount", String.valueOf(idTable.getFloat(idTable.getColumnIndex("amountPay"))));
				Log.d("pay", String.valueOf(idTable.getFloat(idTable.getColumnIndex("calculatedAmount"))));
				payedAmount = idTable.getFloat(idTable.getColumnIndex("amountPay"));
				totalAmount = totalAmount + payedAmount; 
				idTable.moveToNext();
			}
			
			payedAmount = 0;
			int testMod = (int)((totalAmount * 100)%count3);
			Log.d("TestMod", String.valueOf(testMod));
			int testAmount = (int)((totalAmount * 100)/count3);
			Log.d("TestAmount", String.valueOf(testAmount));
			float newAmount = (float)((float)testAmount/100);
			Log.d("NewAmount", String.valueOf(newAmount));
			float newMod = (float)(testMod/100) ;
			Log.d("newMod", String.valueOf(newMod));
			
			for(int i = 0; i < count3; i++)
			{
				fillAmount[i] = newAmount;
				Log.d("FillAmount", String.valueOf(fillAmount[i]));
			}
			for(int j = 0; j < testMod; j++)
			{
				fillAmount[j] = (float)((float)fillAmount[j] *100 + 1);
				fillAmount[j] = (float)((float)fillAmount[j] /100);
				Log.d("FillAmount", String.valueOf(fillAmount[j]));
			}
			Log.d("TotalAmount", String.valueOf(totalAmount));
			/*Log.d("AmountPaid", String.valueOf(payedAmount));*/
			
			for(int fillcount =0; fillcount < count3; fillcount++)
			{
				Log.d("ListAmount1", String.valueOf(listAmount[fillcount]));
				Log.d("FillAmount1", String.valueOf(fillAmount[fillcount]));
				listAmount[fillcount] = (float)(listAmount[fillcount] - fillAmount[fillcount]);
				Log.d("ListAmount2", String.valueOf(listAmount[fillcount]));
			}
			
			int arrSize1 =  count3;
	    	for(int i= 0; i< arrSize1; i++)
			{
				Log.d("amount", amount1[i]);
				String strSQL = "UPDATE'" + fetchEvent + "'SET calculatedAmount = '"+ listAmount[i] + "' WHERE personeName = '"+ name[i] +"'";
				CreateActivity.db.execSQL(strSQL);
				//final String valueNew = "UPDATE'" + fetchEvent + "'SET'" + amountPay =amount1[i]  ";
				//CreateActivity.db.execSQL(valueNew);
			}
	    	
	    	Cursor tableid = CreateActivity.db.rawQuery("SELECT * from " + fetchEvent, null);
			int countnew = tableid.getCount();
			tableid.moveToFirst();
			for(int track1 = 0;track1 < count1; track1++)
			{
				Log.d("NAME", tableid.getString(tableid.getColumnIndex("personeName")));
				Log.d("amount", String.valueOf(tableid.getFloat(tableid.getColumnIndex("amountPay"))));
				Log.d("pay", String.valueOf(tableid.getFloat(tableid.getColumnIndex("calculatedAmount"))));
				tableid.moveToNext();
			}
			Intent i = new Intent(AddexpenseActivity.this, ShowexpenseActivity.class);
			i.putExtra(ShowexpenseActivity.EVENT_POSITION_KEY,eventPosition);
			//i.putExtra(ShowexpenseActivity.EVENT_KEY,totalAmount);
	    	startActivity(i);
	    	finish();
	    	//c.screenUpdate();
			}
	     });
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

	    if (keyCode == KeyEvent.KEYCODE_BACK) {

	    	Intent i = new Intent(AddexpenseActivity.this, CreateActivity.class);
	    	startActivity(i);
	        finish();
	        }
	       	return super.onKeyDown(keyCode, event);
	}
    
}
